import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/person/api/api_person.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

import 'model/my_news_entity.dart';

class NewsPage extends StatefulWidget {
  @override
  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<MyNewsEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  List<MyNewsList> _dataLists = [];

  ///刷新数据
  Future _refresh() async {
    if (_refreshController.isRefresh) {
      page = 1;
    }
    if (_refreshController.isLoading) {
      page += 1;
    }
    setState(() {
      _future = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<MyNewsEntity>> _getData() async {
    var response = await ApiPerson.getMyNews<MyNewsEntity>(
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<MyNewsEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<MyNewsEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              MyNewsEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            bgColor: ThemeColors.colorWhite,
            state: _loadState,
            successWidget: _initList(),
          );
        });
  }

  @override
  void initState() {
    super.initState();
    _future = _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _initAppBar(),
      body: _buildFutureBuilder(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("我的消息", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _refresh,
        onLoading: _refresh,
        child: ListView.separated(
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            MyNewsList model = _dataLists[index];
            return getCell(model: model, onTap: () {});
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              color: ThemeColors.colorType49,
            );
          },
        ));
  }

  Widget getCell({MyNewsList model, GestureTapCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.all(ScreenAdapter.width(30)),
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    model.title ?? "-",
                    style: TextStyle(
                        color: ThemeColors.colorType1,
                        fontSize: ScreenAdapter.sp(30),
                        fontWeight: FontWeight.w500),
                  ),
                  Text(
                    model.createDate ?? "-",
                    style: TextStyle(
                        color: ThemeColors.colorType26,
                        fontSize: ScreenAdapter.sp(24)),
                  ),
                ],
              ),
              SizedBox(height: ScreenAdapter.height(30)),
              Text(model.content ?? "-",
                  textAlign: TextAlign.left,
                  maxLines: 2,
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeColors.colorType26,
                    fontSize: ScreenAdapter.sp(28),
                  )),
            ],
          ),
        ),
      ),
    );
  }
}
